package com.pai.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
 * Properties文件操作类。
 * @author Jeff
 *
 */
public class PropertiesUtil {
	
	private Properties properties;
	
	
	/**
	 * 检查是否加载了properties文件。
	 */
	private void checkPropertyLoading() {
		if (properties == null)
			throw new RuntimeException("You must load properties file by invoking loadPropertyFile(String) method in configConstant(Constants) method before.");
	}
	/**
	 * 加载properties文件
	 * @param filepath 文件地址。(需要为直接能用file()得到的地址)
	 * @return
	 */
	public Properties loadPropertyFile(String filepath){
		if( filepath==null || "".equals(filepath.trim()) ){
			throw new IllegalArgumentException("Properties文件路径不能为空");
		}
		if (filepath.contains(".."))
			throw new IllegalArgumentException("Properties文件 路径不能包括\"..\"");
		
		InputStream inputStream = null;
		
		try {
			inputStream = new FileInputStream(new File(filepath));
			Properties p = new Properties();
			p.load(inputStream);
			properties = p;
		} catch (FileNotFoundException e) {
			throw new IllegalArgumentException("Properties 文件未找到: " + filepath);
		} catch (IOException e) {
			throw new IllegalArgumentException("无法加载 Properties 文件 : " + filepath);
		}
		finally {
			try {if (inputStream != null) inputStream.close();} catch (IOException e) {e.printStackTrace();}
		}
		if (properties == null)
			throw new RuntimeException("无法加载 Properties 文件 : " + filepath);
		return properties;
		
	}
	
	/**
	 * 得到property的值。
	 * @param key 属性名
	 * @return
	 */
	public String getProperty(String key) {
		checkPropertyLoading();
		return properties.getProperty(key);
	}
	
	/**
	 * 测试方法。
	 * @param args
	 */
	public static void main(String[] args){
		PropertiesUtil propertiesUtil = new PropertiesUtil();
		propertiesUtil.loadPropertyFile("src/config.properties");
		System.out.println(propertiesUtil.getProperty("multicast_address"));
		
	}
}
